package logic

import (
	"context"
	"encoding/json"
	"goods/cache"
	"goods/goodsrpc/goodsrpc"
	"goods/goodsrpc/internal/svc"
	"goods/model"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodListLogic {
	return &GoodListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodListLogic) GoodList(in *goodsrpc.GoodListRequest) (*goodsrpc.GoodListResponse, error) {
	// todo: add your logic here and delete this line
	/*
		SELECT
		  goods.*,
		  classes.`name` AS class_name
		 FROM
		  `goods`
		LEFT  JOIN classes ON goods.class_id = classes.id
	*/
	var goodsList []*goodsrpc.GoodList
	result, _ := cache.Rdb.Get(l.ctx, "goodList").Result()
	if result == "" {
		goodsList = model.GoodList(model.DB, goodsList)

		marshal, _ := json.Marshal(&goodsList)

		cache.Rdb.Set(l.ctx, "goodList", marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &goodsList)
	}

	return &goodsrpc.GoodListResponse{
		List: goodsList,
	}, nil
}
